﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using RPAVIEW.util;
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Collections.Generic;
using RestSharp.Extensions;
using SUNRPA.CONTROLS.IMPL.domain.attrubutes;
using SUNRPA.CONTROLS.IMPL.util;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using System.Collections.Concurrent;

namespace RPAVIEW.views.EditPage.flows {
    /// <summary>
    /// FlowItemView.xaml 的交互逻辑
    /// </summary>
    public partial class FlowItemView:UserControl {
        private FlowItemView endTagView;
        private List<FlowItemView> middleTagViews = new List<FlowItemView>();

        public List<FlowItemView> MiddleTagViews {get {return middleTagViews;} set { middleTagViews = value;}}
        public FlowItemView EndTagView {get {return endTagView;} set { endTagView = value;}}

        public FlowItemView(FlowItem item) {
            this.Resources.Add("itemResource", item);
            InitializeComponent();
            if(item.ControlType != null) { 
                this.del.AddHandler(MenuItem.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.DeleteItem), true);
            }
        }

        private void EditFlowItem(object sender, MouseButtonEventArgs e) {
            MainWindow mainWindow = WindowUtil.GetWindow<MainWindow>();
            //置灰
            mainWindow.Opacity = 0.5;
            FlowItem item = (FlowItem)this.FindResource("itemResource");
            if(string.IsNullOrEmpty(item.ControlName)) { 
                return;
            }
            FlowEditWindow editWindow = new FlowEditWindow(item);
            editWindow.Owner = mainWindow;
            editWindow.ShowDialog();
            item.ItemInfo = item.ItemInfo;
            mainWindow.Opacity = 1;
        }

        private void InsterItem(object sender, DragEventArgs e) {
            Border border = (Border)sender;
            string borderName = border.Name;
            FlowItem flowItem = (FlowItem)this.DataContext;
            MainWindow mainWindow = WindowUtil.GetWindow<MainWindow>();
            TreeViewItem targetControl = (TreeViewItem)e.Data.GetData(typeof(TreeViewItem));
            //置灰
            mainWindow.Opacity = 0.5;
            FlowEditWindow flowEditWindow = new FlowEditWindow(targetControl, mainWindow.Content as EditHome);
            if("topBorder".Equals(borderName)) {
                flowEditWindow.InsertIndex = flowItem.Index;
            } else { 
                flowEditWindow.InsertIndex= flowItem.Index + 1;
            }
            border.BorderThickness = new Thickness(0,0,0,0);
            flowEditWindow.IsInsert = true;
            flowEditWindow.Owner = mainWindow;
            flowEditWindow.ShowDialog();
            mainWindow.Opacity = 1;
            e.Handled = true;
        }

        private void ChangeBorder(object sender, DragEventArgs e) {
            Border border = (Border)sender;
            string borderName = border.Name;
            if("topBorder".Equals(borderName)) {
                if("DragEnter".Equals(e.RoutedEvent.Name)) {
                    border.BorderThickness = new Thickness(0,2,0,0);
                } else { 
                    border.BorderThickness = new Thickness(0,0,0,0);
                }
            } else { 
                if("DragEnter".Equals(e.RoutedEvent.Name)) {
                    border.BorderThickness = new Thickness(0,0,0,2);
                } else { 
                    border.BorderThickness = new Thickness(0,0,0,0);
                }
            }
        }

        private void DeleteItem(object sender, MouseButtonEventArgs e) {
            if(((FlowItem)this.DataContext).ControlType == null) {
                //不能直接删除尾部标签
                return;
            }
            MainWindow mainWindow = WindowUtil.GetWindow<MainWindow>();
            EditHome editHome = mainWindow.Content as EditHome;
            int deleteIndex = ((FlowItem)this.DataContext).Index;
            int endIndex = deleteIndex + 1;
            if(this.endTagView != null){ 
                FlowItem endTag = this.endTagView.DataContext as FlowItem;
                endIndex = endTag.Index + 1;
            }
            //删除之前先把将要删除流程项所定义的变量删除
            for(int i = deleteIndex; i < endIndex; i++){
                FlowItemView fiv =  (FlowItemView)editHome.FlowItems.Children[i];
                FlowItem fi = fiv.DataContext as FlowItem;
                BaseParam param = fi.ControlParam;
                if(param != null) { 
                    Type paramType = param.GetType();
                    VarFieldNameAttribute attr = paramType.GetAttribute<VarFieldNameAttribute>();
                    if(attr != null) {
                        string[] varFileds = attr.FieldName;
                        foreach(string fieldName in varFileds) {
                            object varObj = param.GetModelValueByFieldName(fieldName);
                            if(varObj != null) {
                                string varKey = varObj.ToString();
                                ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> runnerContextVarData 
                                    = editHome.DataContext as ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>;
                                runnerContextVarData[DefaultContents.RUNNING_PARAM].TryRemove(varKey, out RPAVariableDefineWrapper temp);
                            }
                        }
                    }
                }
            }
            editHome.FlowItems.Children.RemoveRange(deleteIndex, endIndex - deleteIndex);
            for(int i = deleteIndex; i < editHome.FlowItems.Children.Count; i++) { 
                FlowItemView fiv =  (FlowItemView)editHome.FlowItems.Children[i];
                FlowItem changeIndexItem = fiv.DataContext as FlowItem;
                changeIndexItem.Index = changeIndexItem.Index - endIndex + deleteIndex;
            }
        }
    }

    public class FlowItemInfoConverter:IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            string info = (string)value;
            MatchCollection matches = DefaultContents.PARAM_PATTERN.Matches(info);
            if (matches.Count <= 0) {
                return info;
            }
            FlowItem flowItem = (FlowItem)parameter;
            BaseParam itemParam = flowItem.ControlParam;
            Type parmType = Type.GetType(flowItem.ControlType);
            foreach (Match match in matches) { 
                string field = match.Groups[0].Value.Substring(1,match.Groups[0].Value.Length - 2);
                String fieldValue = "";
                if(parmType.GetMethod("GetTranslate"+field) == null){ 
                    object v = parmType.GetMethod("get_"+field).Invoke(itemParam, null);
                    if(v != null) { 
                        fieldValue = v.ToString();
                    }
                } else { 
                    object v = parmType.GetMethod("GetTranslate"+field).Invoke(itemParam, null);
                    if(v != null) { 
                        fieldValue = v.ToString();
                    }
                }
                info = info.Replace(match.Groups[0].Value, fieldValue);
            }
            return info;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
    }
}
